from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SubmitField,SelectField,BooleanField,ValidationError
from wtforms.validators import Length,DataRequired,Regexp,Email
from flask_pagedown.fields import PageDownField
from config import getLang
from app import const
from app.models import Role,User
from flaskckeditor import CKEditor

EMAIL_LEN = const.EMAIL_LEN
USER_MIN = const.USER_MIN
USER_MAX = const.USER_MAX
PSW_MIN = const.PSW_MIN
PSW_MAX = const.PSW_MAX

class EditProfileForm(FlaskForm):
	name = StringField(getLang("realName"),validators=[Length(0,EMAIL_LEN)]) 
	location = StringField(getLang("address"),validators=[Length(0,EMAIL_LEN)]) 
	about_me = TextAreaField(getLang('aboutMe'))
	submit = SubmitField(getLang('modify'))

class EditProfileAdminForm(FlaskForm):
	username = StringField(getLang('uname',USER_MIN,USER_MAX),validators=[
		DataRequired(getLang('userMsg')),
		Length(USER_MIN,USER_MAX,getLang('userLenTip',USER_MIN,USER_MAX)),
		Regexp('^[^0-9]',0,getLang("unameLegTips")),#设置用户名不能以数字开头 
		]
		)

	email = StringField(getLang('email',EMAIL_LEN),validators=[
		DataRequired(),
		Length(1,EMAIL_LEN),Email(getLang('emailMsg'))])
	confirmed = BooleanField(getLang('isConfirm'))
	role = SelectField(getLang('rolePermission'),coerce=int)
	name = StringField(getLang('realName'))
	location = StringField(getLang("address"),validators=[Length(0,EMAIL_LEN)]) 
	about_me = TextAreaField(getLang('aboutMe'))
	submit = SubmitField(getLang('modify'))

	def __init__(self,user,*args,**kwargs):
		super(EditProfileAdminForm,self).__init__(*args,**kwargs)
		#设置下拉列表的选项
		self.role.choices = [(role.id,role.name) for role in Role.query.order_by(Role.name).all()]
		self.user = user
	def validate_email(self,field):
		if field.data!=self.user.email and User.query.filter_by(email=field.data).first():
			raise ValidationError(getLang('emailRegister'))
	def validate_username(self,field):
		if field.data!=self.user.username and User.query.filter_by(username=field.data).first():
			raise ValidationError(getLang('userRegister'))

class PostForm(FlaskForm):
	title = PageDownField(getLang('posTitleTips',const.POST_TITLE_LEN),validators=[DataRequired("内容不能为空"),Length(1,const.POST_TITLE_LEN)])
	#StringField(getLang('posTitle',const.POST_TITLE_LEN),validators=[Length(1,const.POST_TITLE_LEN)])
	text = PageDownField(getLang('postBodyTips'),validators=[DataRequired(getLang('contentNull'))])
	submit = SubmitField(getLang('submitLbl'))

#评论表单
class CommentsForm(FlaskForm):
	body = PageDownField(getLang('commnetsHead'),validators=[DataRequired(getLang('contentNull'))])
	submit = SubmitField(getLang('commentsBtn'))

class CKDemoForm(FlaskForm,CKEditor):
	editor = TextAreaField()	
	submit = SubmitField("提交")